﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Net;
using System.Xml.Serialization;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Collections;

public partial class Default3 : System.Web.UI.Page
{
    string jscript = string.Empty;
    string Deliverscript = string.Empty;
    string DeliverscriptOnIndexChange = string.Empty;
    string jscriptOnIndexChange = string.Empty;
    string jscriptInstamapper = string.Empty;
    ArrayList RefershRate = new ArrayList();
    ArrayList Time = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["CookieUserID"] == null)
        {
            Response.Redirect("Login.aspx");
        }

        else
        {
            if (!IsPostBack)
            {
                lblLocaltime.Text = DateTime.Now.AddHours(-5).ToShortDateString() + "  " + ConvertToUnixTimestamp(DateTime.Now.AddHours(-5).ToShortDateString() + " 09:00:00" + ddlAmPm.SelectedItem.Text);
                GetAQllZohoDeliverers(ConvertToUnixTimestamp(DateTime.Now.AddHours(-5).ToShortDateString() + " 09:00:00" + ddlAmPm.SelectedItem.Text), "500");

                BindDropDowns();
            }
        }
        if (Request.Cookies["CookieUserID"] != null)
        {
            HttpCookie CookieID;
            CookieID = Request.Cookies["CookieUserID"];

            //divChangePassword.Visible = true;

        }

    }
    public void GetAQllZohoDeliverers(string MonitorStartTime, string NumerOfInstaPlots)
    {
        HttpWebRequest request = WebRequest.Create("https://creator.zoho.com/api/json/king-telemarketing-system/view/InfoDeliverers?authtoken=aad0610e3363259d479310ddb9363b9c&scope=creatorapi&zc_ownername=avanci01&raw=true") as HttpWebRequest;
        request.Method = "GET";

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            string str = reader.ReadToEnd();

            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            DeliverersCollection Alldeliverers = (DeliverersCollection)(oSerializer.Deserialize(str, typeof(DeliverersCollection)));
            DataTable dtdeliver = new DataTable();
            dtdeliver.Columns.Add(new DataColumn("Deliverer"));
            dtdeliver.Columns.Add(new DataColumn("InstamapperAPIkey"));
            dtdeliver.Columns.Add(new DataColumn("Zoho_Authtoken"));
            dtdeliver.Columns.Add(new DataColumn("PathColor"));


            foreach (Deliverers DeliverName in Alldeliverers.EJECUTIVOS)
            {
                DataRow row = dtdeliver.NewRow();
                row["Deliverer"] = DeliverName.Empleado;
                row["InstamapperAPIkey"] = DeliverName.InstamapperAPIkey;
                row["Zoho_Authtoken"] = DeliverName.Zoho_Authtoken;
                row["PathColor"] = DeliverName.PathColor;


                dtdeliver.Rows.Add(row);
            }

            gvMain.DataSource = dtdeliver;
            gvMain.DataBind();
            string JsScript = string.Empty;
            for (int i = 0; i <= gvMain.Rows.Count; i++)
            {
               // if (i>0)
                //{
                try
                {
                    JsScript = PlaceZohoCustomersAndInstaMaper(((Label)(gvMain.Rows[i].FindControl("lblAuthToken"))).Text, ((Label)(gvMain.Rows[i].FindControl("lblInstamapperAPIkey"))).Text, i.ToString(), ((Label)(gvMain.Rows[i].FindControl("lblPathColor"))).Text, MonitorStartTime, NumerOfInstaPlots, ((Label)(gvMain.Rows[i].FindControl("lbldeliverer"))).Text, ((CheckBox)gvMain.Rows[i].FindControl("chkDeliverer")).Checked, ((CheckBox)gvMain.Rows[i].FindControl("chkNewDeliverer")).Checked);
                }
                catch (Exception)
                {
                    continue;
                }
                //}
            }
            js.Text = "<script type=\"text/javascript\"> var markersArray= []; var markerIndex=-1; $(document).ready(function () { var obj; var infowindow = new google.maps.InfoWindow();  " + JsScript + " });   </script>";
            //js.Text = "<script type=\"text/javascript\">var map; var infowindow = new google.maps.InfoWindow(); var marker, i;function initialize() {" + JsScript + "}</script>";
        }
    }

    public string PlaceZohoCustomersAndInstaMaper(string Zoho_Authtoken, string InstamapperAPIkey, string keyIndexForChange, string PathColor, string MonitorStartTime, string NumerOfInstaPlots, string DelivererName, bool Acciones, bool AccionesESP)
    {
        if (Acciones)
        {
            Deliverscript = GetZohoCustomers(Zoho_Authtoken, keyIndexForChange, PathColor, "Acciones_del_dia");
        }
        if (AccionesESP)
            DeliverscriptOnIndexChange = GetZohoCustomers(Zoho_Authtoken, keyIndexForChange, PathColor, "Acciones_Esp_del_dia");
        if (Acciones || AccionesESP)
           jscriptOnIndexChange = CreateInstaMapperPlot(InstamapperAPIkey, NumerOfInstaPlots, MonitorStartTime, keyIndexForChange, PathColor, DelivererName);

        return jscript += Deliverscript + DeliverscriptOnIndexChange + jscriptOnIndexChange;
    }
    public string GetZohoCustomers(string Zoho_Authtoken, string keyIndexForChange, string PathColor, string View)
    {
        HttpWebRequest requestCustomers = WebRequest.Create("https://creator.zoho.com/api/json/king-telemarketing-system/view/" + View + "?authtoken=" + Zoho_Authtoken + "&scope=creatorapi&zc_ownername=avanci01&raw=true") as HttpWebRequest;
        requestCustomers.Method = "GET";
        HttpWebResponse responseCustomers;
        responseCustomers = requestCustomers.GetResponse() as HttpWebResponse;
        if (responseCustomers.StatusCode == HttpStatusCode.OK)
        {
            Stream responseCustomerStream = responseCustomers.GetResponseStream();
            StreamReader readerCustomer = new StreamReader(responseCustomerStream);
            string strCusotmer = readerCustomer.ReadToEnd();
            if (strCusotmer != "{\"ACCIONES\":[]}")
            {
                jscript += "var i; obj = " + strCusotmer + @";
            $.each(obj.ACCIONES, function () {

                 var latLng = new google.maps.LatLng(this['Latitud'],this['Longitud']);
                 var Lat=this['Latitud']; var Long=this['Longitud']; var Nombre_Moral_Fisica=this['Nombre_Moral_Fisica'];
                 var Numero_de_Cliente=this['Numero_de_Cliente'];var Numero_SAE=this['Numero_SAE'];
                 var Ejecutivo=this['Ejecutivo'] ; var Accion_a_Realizar =this['Accion_a_Realizar'];
                 var Comentarios=this['Comentarios']; var Colonia=this['Colonia'];
                 var OK=this['OK'];
var image='';
                if (OK == 'OK') {
            image = 'images/green.png';
        }
        else {
            image = 'images/" + PathColor + @".png';
        }

                 var marker = new google.maps.Marker
                              ({  

                              position: latLng,  
                              map: map,icon: image,  
                              draggable: false

                              });
                     google.maps.event.addListener(marker, 'click', (function (marker, i) 
                            { 
                            
                               return function () 
                                  {  
                                     infowindow.setContent('<div>Nombre_Moral_Fisica:'+Nombre_Moral_Fisica+'<br>Numero_de_Cliente:'+Numero_de_Cliente+' <br> Numero_SAE:'+Numero_SAE+'<br>Ejecutivo:'+Ejecutivo+'<br/><br/>Accion_a_Realizar:'+Accion_a_Realizar+' <br/><br/>Comentarios:'+Comentarios+'  <br/><br/>Colonia:'+Colonia+' <br>N:'+Lat+' <br>W:'+Long+'</div>');
                                     infowindow.open(map, marker);
                                  }
                             }) (marker, i)); 
                });";

                return jscript;
            }
            else
                return jscript = "";
        }
        else {
            return "";
        }
        //    System.Web.Script.Serialization.JavaScriptSerializer oSerializerCustomer = new System.Web.Script.Serialization.JavaScriptSerializer();
        //    CustomerCollection AllCustomers = (CustomerCollection)(oSerializerCustomer.Deserialize(strCusotmer, typeof(CustomerCollection)));
        //    DataTable dt = new DataTable();
        //    dt.Columns.Add(new DataColumn("Latitude"));
        //    dt.Columns.Add(new DataColumn("Longitude"));
        //    dt.Columns.Add(new DataColumn("Nombre_Moral_Fisica"));
        //    dt.Columns.Add(new DataColumn("Accion_a_Realizar"));
        //    dt.Columns.Add(new DataColumn("Comentarios"));
        //    dt.Columns.Add(new DataColumn("Numero_de_Cliente"));
        //    dt.Columns.Add(new DataColumn("Pedido"));
        //    dt.Columns.Add(new DataColumn("Colonia"));
        //    dt.Columns.Add(new DataColumn("Numero_SAE"));
        //    dt.Columns.Add(new DataColumn("Orden_en_la_Ruta"));
        //    dt.Columns.Add(new DataColumn("OK"));
        //    dt.Columns.Add(new DataColumn("Fecha_Accion"));
        //    dt.Columns.Add(new DataColumn("ID"));
        //    dt.Columns.Add(new DataColumn("Ejecutivo"));

        //    foreach (customers Customer in AllCustomers.ACCIONES)
        //    {
        //        if (Customer.Latitud != "" && Customer.Longitud != "")
        //        {
        //            DataRow row = dt.NewRow();
        //            row["Latitude"] = Customer.Latitud;
        //            row["Longitude"] = Customer.Longitud;
        //            row["Nombre_Moral_Fisica"] = Customer.Nombre_Moral_Fisica;
        //            row["Accion_a_Realizar"] = Customer.Accion_a_Realizar;
        //            row["Comentarios"] = Customer.Comentarios;
        //            row["Numero_de_Cliente"] = Customer.Numero_de_Cliente;
        //            row["Pedido"] = Customer.Pedido;
        //            row["Colonia"] = Customer.Colonia;
        //            row["Numero_SAE"] = Customer.Numero_SAE;
        //            row["Orden_en_la_Ruta"] = Customer.Orden_en_la_Ruta;
        //            row["OK"] = Customer.OK;
        //            row["Fecha_Accion"] = Customer.Fecha_Accion;
        //            row["ID"] = Customer.ID;
        //            row["Ejecutivo"] = Customer.Ejecutivo;
        //            dt.Rows.Add(row);
        //        }
        //    }
        //    if (dt.Rows.Count > 0)
        //        jscriptInstamapper = GPSLib.AddCutomerMarkerAndInfo(dt, keyIndexForChange, PathColor, false, chkIsNameVisible.Checked);
        //}
        //return jscriptInstamapper;
    }

    public String CreateInstaMapperPlot(string InstamapperAPIkey, string NumerOfInstaPlots, string MonitorStartTime, string keyIndexForChange, string PathColor, string DelivererName)
    {
        string jscriptInstaMaper = string.Empty;
        string strWebURL = "http://www.instamapper.com/api?action=getPositions&key=" + InstamapperAPIkey + "&num=" + NumerOfInstaPlots + "&format=json";
        if (MonitorStartTime != "0")
            strWebURL += "&from_ts=" + MonitorStartTime;
        HttpWebRequest requestCustomers = WebRequest.Create(strWebURL) as HttpWebRequest;
        requestCustomers.Method = "GET";
        HttpWebResponse responseCustomers = requestCustomers.GetResponse() as HttpWebResponse;
        if (responseCustomers.StatusCode == HttpStatusCode.OK)
        {
            Stream responseCustomerStream = responseCustomers.GetResponseStream();
            StreamReader readerCustomer = new StreamReader(responseCustomerStream);
            string strDeliverersPosition = readerCustomer.ReadToEnd();
            System.Web.Script.Serialization.JavaScriptSerializer oSerializerDeliverersPosition = new System.Web.Script.Serialization.JavaScriptSerializer();
            DeliverersPositionCollection AllDeliverersPosition = (DeliverersPositionCollection)(oSerializerDeliverersPosition.Deserialize(strDeliverersPosition, typeof(DeliverersPositionCollection)));
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Latitude"));
            dt.Columns.Add(new DataColumn("Longitude"));
            dt.Columns.Add(new DataColumn("device_key"));
            dt.Columns.Add(new DataColumn("heading"));
            dt.Columns.Add(new DataColumn("speed"));
            dt.Columns.Add(new DataColumn("timestamp"));
            foreach (DelivererPosition DeliverersPosition in AllDeliverersPosition.positions)
            {
                if (DeliverersPosition.latitude != "" && DeliverersPosition.longitude != "")
                {
                    DataRow row = dt.NewRow();
                    row["Latitude"] = DeliverersPosition.latitude;
                    row["Longitude"] = DeliverersPosition.longitude;
                    row["device_key"] = DeliverersPosition.device_key;
                    row["heading"] = DeliverersPosition.heading;
                    row["speed"] = DeliverersPosition.speed;
                    row["timestamp"] = DeliverersPosition.timestamp;
                    dt.Rows.Add(row);
                }
            }
            if (dt.Rows.Count > 0)
                jscriptInstaMaper = GPSLib.AddInstamaperPlots(dt, keyIndexForChange, PathColor, true, chkIsNameVisible.Checked, DelivererName);

        }

        return jscriptInstaMaper;

    }


    public static string ConvertToUnixTimestamp(string date)
    {
        // date =  TimeZoneInfo.ConvertTimeBySystemTimeZoneId(date, TimeZoneInfo.Local.Id, ddlTimeZone.SelectedValue).ToString();

        DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);

        TimeSpan diff = Convert.ToDateTime(date).AddHours(-5) - origin;

        //return "1344002400";
        return Convert.ToInt32(Math.Floor(diff.TotalSeconds)).ToString();

    }


    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string JsScript = string.Empty;
        DateTime date = new DateTime();
        date = DateTime.Now;
        string h = ddlTime.SelectedValue;
        string T = DateTime.Now.AddHours(-5).ToShortDateString() + " " + ddlTime.SelectedValue+ ":00:00" + ddlAmPm.SelectedItem.Text;
        lblLocaltime.Text = DateTime.Now.AddHours(-5).ToString() + "  " + ConvertToUnixTimestamp(T);
        for (int i = 0; i <= gvMain.Rows.Count; i++)
        {
            try
            {
                JsScript += PlaceZohoCustomersAndInstaMaper(((Label)(gvMain.Rows[i].FindControl("lblAuthToken"))).Text, ((Label)(gvMain.Rows[i].FindControl("lblInstamapperAPIkey"))).Text, i.ToString(), ((Label)(gvMain.Rows[i].FindControl("lblPathColor"))).Text, ConvertToUnixTimestamp(T), txtNumber.Text, ((Label)(gvMain.Rows[i].FindControl("lbldeliverer"))).Text, ((CheckBox)gvMain.Rows[i].FindControl("chkDeliverer")).Checked, ((CheckBox)gvMain.Rows[i].FindControl("chkNewDeliverer")).Checked);
            }
            catch (Exception)
            {
                continue;
            }
        }


        js.Text = "<script type=\"text/javascript\"> var markersArray= []; var markerIndex=-1; $(document).ready(function () { var obj; var infowindow = new google.maps.InfoWindow();  " + JsScript + " });   </script>";
        if (ddlRefershRate.SelectedValue != "0")
        {
            LtrlPathFollowed.Text = "<script type=\"text/javascript\">	var timer;  function ReloadPage() {$(\"#btnSearch\").click();};$(document).ready(function () {timer = setTimeout(\"ReloadPage()\"," + Convert.ToInt32(ddlRefershRate.SelectedValue) * 60 * 1000 + ");});</script>";
            LtrlPathFollowed.Text += "<script type=\"text/javascript\">function stoptimer() {clearTimeout(timer);}</script>";
        }
    }
    public void BindDropDowns()
    {

        for (int i = 0; i <= 20; i = i + 2)
        {
            RefershRate.Add(i);
        }
        ddlRefershRate.DataSource = RefershRate;
        ddlRefershRate.DataBind();
        for (int Tim = 0; Tim <= 12; Tim++)
        {
            Time.Add(Tim);
        }
        ddlTime.DataSource = Time;
        ddlTime.DataBind();
        ddlTime.SelectedValue = "9";
    }

    protected void lnkLogOut_Click(object sender, EventArgs e)
    {

        HttpCookie CookieUserID = new HttpCookie("CookieUserID");
        CookieUserID.Expires = DateTime.Now.AddDays(-30);

        Response.Cookies.Add(CookieUserID);

        Response.Redirect("Login.aspx");
    }

}
